import { baseLogUrl } from '@/api/api.request';
/**
 * 获取cookie
 */
function getCookie(name: string): string {
    let arr: RegExpMatchArray;
    const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
    const temp = document.cookie.match(reg);
    if (temp !== null && temp !== undefined) {
        arr = temp;
        return decodeURIComponent(arr[2]);
    }
    return '';
}

/**
 * 存cookie
 */
function setCookie(name: string, value: string, expiresDate = 24) {
    const date = new Date(); // 获取当前时间
    date.setTime(date.getTime() + expiresDate * 3600 * 1000); // 格式化为cookie识别的时间
    document.cookie = `${name}=${value};expires=${date.toUTCString()}`;
}

/**
 * 删除cookie
 */
function deleteCookie(name: string) {
    setCookie(name, '', -1);
}

function formatDate(date: any, fmt: any) {
    const dates = new Date(date);
    const o = {
        'y+': dates.getFullYear(),
        'M+': dates.getMonth() + 1, // 月份
        'd+': dates.getDate(), // 日
        'h+': dates.getHours(), // 小时
        'm+': dates.getMinutes(), // 分
        's+': dates.getSeconds(), // 秒
        'q+': Math.floor((dates.getMonth() + 3) / 3), // 季度
        S: dates.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, `${dates.getFullYear()}`.substr(4 - RegExp.$1.length));
    Object.keys(o).forEach((k) => {
        if (new RegExp(`(${k})`).test(fmt)) {
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
        }
    });
    return fmt;
}

function formatDateBeiJing(dates: any, fmt: any, name: any) {
    const date = new Date(dates);
    const timestampUtc = date.getTime() / 1000;
    const timestamp: any = name === 'UCT' ? timestampUtc - 8 * 60 * 60 : timestampUtc + 8 * 60 * 60;
    return formatDate(new Date(parseInt(timestamp, 10) * 1000), fmt);
}

let timeout: any = null;
function debounce(fn: any, wait: any) {
    if (timeout !== null) clearTimeout(timeout);
    timeout = setTimeout(fn, wait);
}

// 转formData数据
function objectToFormData(obj: any) {
    let formData = new FormData();
    Object.keys(obj).forEach((key) => {
        if (obj[key] instanceof Array) {
            obj[key].forEach((item: any) => {
                formData.append(key, item);
            });
            return;
        }
        formData.append(key, obj[key]);
    });
    return formData;
}
function directiveLog(app: any) {
    let actCurrentTime;
    app.directive('logAction', (el: any, binding: any) => {
        el.addEventListener(
            'click',
            () => {
                const token = getCookie('SaaS_Token') ? getCookie('SaaS_Token') : '';
                // 发送请求
                const { value } = binding;
                actCurrentTime = Date.now();
                const actData = {
                    model: 'saas-housekeeper-web-tenant',
                    page: value.page.replace(/\//g, '_').slice(1),
                    ts: actCurrentTime,
                    token: token, // 保存的token
                };
                const actions: any[] = [
                    {
                        item: value.item,
                        descriptions: value.descriptions,
                    },
                ];
                const actData2 = objectToFormData(actData);
                actData2.append('actions', JSON.stringify(actions));
                navigator.sendBeacon(baseLogUrl + 'log/logger', actData2);
            },
            false,
        );
    });
}
function routerGuard(router: any) {
    let startTime = Date.now();
    let currentTime;
    router.beforeEach((to: any, from: any, next: any) => {
        if (to) {
            const token = getCookie('SaaS_Token') ? getCookie('SaaS_Token') : '';
            if (!to.matched.length) {
                next({ path: '/login' });
            } else {
                next();
            }
            /// //////////////////////数据埋点//////////////////////////////////////
            // 页面切换时间
            currentTime = Date.now();
            const time = `${(currentTime - startTime) / 1000}`;
            // 通过计算currentTime - startTime 的 差值 之后，再上报数据
            const page = to.path.replace(/\//g, '_').slice(1);
            const pageData = {
                model: 'saas-housekeeper-web-tenant',
                page: to.path.replace(/\//g, '_').slice(1), // 本页路由
                ts: currentTime, // 跳入时间戳
                token: token, // 保存的token
            };
            const information: any = {
                duringTime: parseInt(`${time}`, 10), // 上一页停留时间
                lastPageId: from.path.replace(/\//g, '_').slice(1), // 上一页路由
                pageId: to.fullPath.replace(/\//g, '_').slice(1), // 本页完整页路由
            };
            const pageData2 = objectToFormData(pageData);
            pageData2.append('information', JSON.stringify(information));
            navigator.sendBeacon(baseLogUrl + 'log/logger', pageData2);
            // 初始化开始时间
            startTime = Date.now();
            /// ////////////////////////////////////////////////////////////
        }
    });
}

export { setCookie, getCookie, deleteCookie, formatDateBeiJing, debounce, objectToFormData, directiveLog, routerGuard };
